<?php

class db_mysql {

    var $version = '';
    var $querynum = 0;
    var $link;

    function connect($dbhost, $dbuser, $dbpw, $dbname = '', $pconnect = 0, $halt = TRUE, $dbcharset2 = '') {

        $func = empty($pconnect) ? 'mysql_connect' : 'mysql_pconnect';
        if (!$this->link = @$func($dbhost, $dbuser, $dbpw, 1)) {
            $halt && $this->halt("数据库连接失败");
        } else {
            if ($this->version() > '4.1') {
                global $charset, $dbcharset;
                $dbcharset = $dbcharset2 ? $dbcharset2 : $dbcharset;
                $dbcharset = !$dbcharset && in_array(strtolower($charset), array('gbk', 'big5', 'utf8')) ? str_replace('-', '', $charset) : $dbcharset;
                $serverset = $dbcharset ? 'character_set_connection=utf8_general_ci, character_set_results=utf8, character_set_client=utf8' : '';
                $serverset .= $this->version() > '5.0.1' ? ((empty($serverset) ? '' : ',') . 'sql_mode=\'\'') : '';
                $serverset && mysql_query("SET $serverset", $this->link);
            }
            $dbname && @mysql_select_db($dbname, $this->link);
        }
    }

    /* 	选择数据库 	 */

    function select_db($dbname) {
        return mysql_select_db($dbname, $this->link);
    }

    /* 	取回查询结果的所有行到数组 	 */

    function fetch_array($query, $result_type = MYSQL_ASSOC) {
        return mysql_fetch_array($query, $result_type);
    }

    /* 	取回查询结果的一行记录到数组 	 */

    function fetch_first($sql) {
        return $this->fetch_array($this->query($sql));
    }

    /* 	取回查询结果的第一个字段值 	 */

    function result_first($sql) {
        return $this->result($this->query($sql), 0);
    }

    /* 	执行查询语句，返回查询的ID句柄 	 */

    function query($sql, $type = '') {

        global $debug, $discuz_starttime, $sqldebug, $sqlspenttimes;
        $func = $type == 'UNBUFFERED' && @function_exists('mysql_unbuffered_query') ?
                'mysql_unbuffered_query' : 'mysql_query';
        if (!($query = $func($sql, $this->link))) {
            if ($type != 'SILENT' && substr($type, 5) != 'SILENT') {
                $this->halt('MySQL Query Error', $sql);
            }
        }

        $this->querynum++;
        return $query;
    }

    /* 	取回查询结果的影响行数 	 */

    function affected_rows() {
        return mysql_affected_rows($this->link);
    }

    function error() {
        return (($this->link) ? mysql_error($this->link) : mysql_error());
    }

    function errno() {
        return intval(($this->link) ? mysql_errno($this->link) : mysql_errno());
    }

    function result($query, $row) {
        $query = @mysql_result($query, $row);
        return $query;
    }

    function num_rows($query) {
        $num = mysql_num_rows($query);
        return $num;
    }

    function num_fields($query) {
        return mysql_num_fields($query);
    }

    function free_result($query) {
        return mysql_free_result($query);
    }

    function insert_id() {
        return ($id = mysql_insert_id($this->link)) >= 0 ? $id : $this->result($this->query("SELECT last_insert_id()"), 0);
    }

    function fetch_row($query) {
        $query = mysql_fetch_row($query);
        return $query;
    }

    function fetch_fields($query) {
        return mysql_fetch_field($query);
    }

    function version() {
        if (empty($this->version)) {
            $this->version = mysql_get_server_info($this->link);
        }
        return $this->version;
    }

    function close() {
        return mysql_close($this->link);
    }

    //
    /**
     * 插入数据 
     * 
     * @param string $table         表名<br /> 
     * @param array $field_values   数据数组<br /> 
     * @return id                   最后插入ID 
     */
    function save($table, $field_values) {
        $fields = array();
        $values = array();
        $field_names = $this->getCol('DESC ' . $table);

        foreach ($field_names as $value) {
            if (array_key_exists($value, $field_values) == true) {
                $fields [] = $value;
                $values [] = "'" . $field_values [$value] . "'";
            }
        }
        if (!empty($fields)) {
            $sql = 'INSERT INTO ' . $table . ' (' . implode(',', $fields) . ') VALUES (' . implode(',', $values) . ')';
            if ($this->query($sql)) {
                return $this->insert_id();
            }
        }
        return false;
    }

    /**
     * 更新数据 
     * 
     * @param string $table         要更新的表<br /> 
     * @param array $field_values   要更新的数据，使用而为数据例:array('列表1'=>'数值1','列表2'=>'数值2') 
     * @param string $where         更新条件 
     * @return bool  
     */
    function update($table, $field_values, $where = '') {
        $field_names = $this->getCol('DESC ' . $table);
        $sets = array();
        foreach ($field_names as $value) {
            if (array_key_exists($value, $field_values) == true) {
                $sets [] = $value . " = '" . $field_values [$value] . "'";
            }
        }
        if (!empty($sets)) {
            $sql = 'UPDATE ' . $table . ' SET ' . implode(', ', $sets) . ' WHERE ' . $where;
        }
        if ($sql) {
            return $this->query($sql);
        } else {
            return false;
        }
    }

    /**
     * 删除数据 
     * 
     * @param string $table 要删除的表<br /> 
     * @param string $where 删除条件，默认删除整个表 
     * @return bool 
     */
    function delete($table, $where = '') {
        if (empty($where)) {
            $sql = 'DELETE FROM ' . $table;
        } else {
            $sql = 'DELETE FROM ' . $table . ' WHERE ' . $where;
        }
        if ($this->query($sql)) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 获取列  
     * 
     * @param string $sql 
     * @return array 
     */
    function getCol($sql) {
        $res = $this->query($sql);
        if ($res !== false) {
            $arr = array();
            $row = mysql_fetch_row($res);
            while ($row) {
                $arr [] = $row [0];
                $row = mysql_fetch_row($res);
            }
            return $arr;
        } else {
            return false;
        }
    }

    //从结果集提取当前行，以字段名和数字为key表示的关联数组形式返回
    function fetch_array_all($sql) {
        $info = array();
        $result = mysql_query($sql, $this->link);
        while ($rec = mysql_fetch_array($result, MYSQL_ASSOC)) {
            $info[] = $rec;
        }
        return $info;
    }

    function halt($message = '', $sql = '') {
        echo "<html xmlns='http://www.w3.org/1999/xhtml'><head><title>$very[name]</title><style type='text/css'>BODY{FONT-FAMILY:tahoma,arial,sans-serif;FONT-SIZE:14px;}</style><body>";
        echo "<div style='border:1px solid #c7dd71;background:#effeb9;padding:10px;'>" . $message;
        echo "<br><br><b>详细信息</b>:<br>" . $this->error() . "  ( " . $this->errno() . " )";
        //echo("无法显示网页，可能是网络问题。请重新刷新页面");
        echo "</div>";
        exit;
    }

}

?>